import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { type User, type UserRole } from '@/types/system/user.ts';
import { getUserInfo } from '@/api/system/auth';

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(localStorage.getItem('token') || '');
  const userInfo = ref<User>({} as User);
  const roles = ref<UserRole[]>([]);

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken;
    localStorage.setItem('token', newToken);
  };

  // 清除token
  const clearToken = () => {
    token.value = '';
    localStorage.removeItem('token');
  };

  // 设置用户信息
  const setUserInfo = (user: User) => {
    userInfo.value = user;
    roles.value = user.roles || [];
  };

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {} as User;
    roles.value = [];
  };

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const res = await getUserInfo();
      setUserInfo(res.data);
      return res.data;
    } catch (error) {
      clearUserInfo();
      throw error;
    }
  };

  // 登出
  const logout = () => {
    clearToken();
    clearUserInfo();
  };

  // 判断是否有某个角色
  const hasRole = (role: UserRole) => {
    return roles.value.includes(role);
  };

  // 判断是否已登录
  const isLoggedIn = computed(() => !!token.value);

  return {
    token,
    userInfo,
    roles,
    isLoggedIn,
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo,
    fetchUserInfo,
    logout,
    hasRole
  };
});
